import { handleActions } from "redux-actions";
import {
    GET_PRODUCT,
    SET_CUR_PAGE,SET_EACH_PAGE,SEARCH_PRODUCT
} from "../types";
import _ from "lodash";

const initData = {
  curPage: 1,
  eachPage: 10,
  total: 0,
  maxPage: 0,
  rows: [],
  _id: "",
};

export const getProduct = handleActions(
  {
    [GET_PRODUCT]: (state, { payload }) => {
      const { total, maxPage, rows } = payload;
      return _.assign({}, state, { total, maxPage, rows });
    },
    [SET_CUR_PAGE]: (state, { payload }) => {
      const { curPage } = payload;
      const $state = _.clone(state);
      $state.curPage = curPage;
      return $state;
    },
    [SET_EACH_PAGE]: (state, { payload }) => {
      const { eachPage } = payload;
      const newState = _.clone(state);
      //改变每页条数获取新数据前将原数据清空，避免console警告
      newState.rows = [];
      newState.eachPage = eachPage;
      return newState;
    },
    [SEARCH_PRODUCT]: (state, { payload }) => {
      const { data } = payload;
      const $state = _.clone(state);
      $state.rows = data;
      console.log($state.rows);
      $state.total = data.length;
      return $state;
    },
  },
  initData
);
